/**
 * @purpose
 * @author daizs
 * @created Mar 8, 2010
 */
package platform.util;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.apache.log4j.Logger;

public class DateUtil {
	private static final Logger log = Logger.getLogger(DateUtil.class);
	public static Locale DEFAULT_LOCALE = Locale.CHINA;
	private static final String DATE_DEFAULT_FORMAT = "yyyy-MM-dd";
	private static final String TIME_DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
	private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // 默认的日期格式
	private static final SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 默认的时间格式
	/**
	 * 
	 * <br/>方法描述:date格式化为日期字符串（默认方法） 
	 * @param date  需要格式化的日期
	 * @return  按照yyyy-MM-dd格式化后的日期字符串
	 */			
	public static String dateToString(Date date){
		return dateToString(date,null,null);
	}
	/**
	 * 
	 * <br/>方法描述:将date格式化为日期字符串 
	 * @param date  需要格式化的日期
	 * @param format  格式化字符串
	 * @param locale  本地 
	 * @return  format格式化的日期字符串
	 */			
	public static String dateToString(Date date, String format, Locale locale) {
	    if (date == null)
	      return "";
	    if (locale == null)
	      locale = DEFAULT_LOCALE;
	    if (format == null)
	      format = DATE_DEFAULT_FORMAT;
	    SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
	    return sdf.format(date);
	  }
	/**
	 * 
	 * <br/>方法描述:date格式化为时间字符串（默认方法） 
	 * @param date  需要格式化的日期
	 * @return  按照yyyy-MM-dd格式化后的日期字符串
	 */			
	public static String timeToString(Date date){
		return timeToString(date,null,null);
	}
	/**
	 * 
	 * <br/>方法描述:将date格式化为时间字符串 
	 * @param date  需要格式化的日期
	 * @param format  格式化字符串
	 * @param locale  本地 
	 * @return  format格式化的时间字符串
	 */			
	public static String timeToString(Date date, String format, Locale locale) {
	    if (date == null)
	      return "";
	    if (locale == null)
	      locale = DEFAULT_LOCALE;
	    if (format == null)
	      format = TIME_DEFAULT_FORMAT;
	    SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
	    return sdf.format(date);
	  }

	/**
	 * 
	 * <br/>方法描述:将date格式为时间字符串 eg:2010-04-20 08：01：10
	 * @param date  需要格式化的日期
	 * @return  按照yyyy-MM-dd HH:mm:ss格式化后的时间字符串
	 */			
	public static String formatTime(Date date) {
		return time.format(date);
	}
	/**
	 * 
	 * <br/>方法描述:将日期字符串解析为date  
	 * @param source  被解析的日期字符串
	 * @return date
	 */			
	public static java.sql.Date praseSqlDate(String source) {
		try {
			return new java.sql.Date(df.parse(source).getTime());
		} catch (ParseException e) {
			log.info("不能转换成日期的字符串 :: " + source);
			return null;
		}
	}
	/**
	 * 
	 * <br/>方法描述:将时间字符串解析为date  
	 * @param source  被解析的时间字符串
	 * @return date
	 */			
	public static java.sql.Date praseSqlTime(String source) {
		try {
			return new java.sql.Date(time.parse(source).getTime());
		} catch (ParseException e) {
			log.info("不能转换成日期的字符串 :: " + source);
			return null;
		}
	}
	/**
	 * 
	 * <br/>方法描述:获得当前月
	 *   
	 * @return 当前月字符串 1-9的范围内增加了0前缀
	 */			
	public static String getCurrentMonth() {
		Calendar cal = new GregorianCalendar();
		int month = cal.get(Calendar.MONTH) + 1;
		if (month == 13)
			month = 12;
		String monthstr = month + "";
		if (monthstr.length() == 1) {
			monthstr = "0" + month;
		}
		return monthstr.toString();
	}
	/**
	 * 
	 * <br/>方法描述:获得当前年
	 *   
	 * @return 当前年字符串
	 */			
	public static String getCurrentYear() {
		Calendar cal = new GregorianCalendar();
		int year = cal.get(Calendar.YEAR);
		return String.valueOf(year);
	}
	/**
	 * 
	 * <br/>方法描述:获得当前日期字符串 yyyy-mm-dd
	 *   
	 * @return 当前年字符串
	 */				
	public static String getCurrentDate() {
		java.util.Date b = new Date();
		String date = "";
		try {
			date = df.format(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}
	
	public static Integer getCurrentDateNoLine() {
		java.util.Date b = new Date();
		SimpleDateFormat dfNoLine = new SimpleDateFormat("yyyyMMddHH"); 
		Integer date = null;
		try {
			date = Integer.valueOf(dfNoLine.format(b));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}
	
	/**
	 * 获取China地区日期时间
	 *
	 * @return yyyy-MM-dd hh:mm:ss形的时间字符串
	 */
	public static String getDate() {
		java.util.Date b = new Date();
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", java.util.Locale.CHINESE);
		return formatter.format(b);
	}
	
	/**
	 * 获取China地区日期时间
	 *
	 * @return yyyy-MM-dd hh:mm:ss形的时间字符串
	 */
	public static String getDate(String gs) {
		java.util.Date b = new Date();
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(gs, java.util.Locale.CHINESE);
		return formatter.format(b);
	}
	
	/**
	 * 获取China地区日期时间
	 *
	 * @return yyyy-MM-dd hh:mm:ss形的时间字符串
	 */
	public static String getHour() {
		java.util.Date b = new Date();
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
				"HH", java.util.Locale.CHINESE);
		return formatter.format(b);
	}
	
	/**
	 * 获取China地区日期时间
	 *
	 * @return yyyy-MM-dd hh:mm:ss形的时间字符串
	 */
	public static String getTime(String time,String gs,String getGs) {
		if(gs == null || gs.equals("")){
			gs = TIME_DEFAULT_FORMAT;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(gs, java.util.Locale.CHINESE);
		Date date = null;
		if(time == null || time.equals("")){
			date = new Date();
		}
		try {
			date = formatter.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		SimpleDateFormat sdf = new SimpleDateFormat(getGs, java.util.Locale.CHINESE);
		return sdf.format(date);
	}
	
	public static String getDate(Integer day){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar cal = Calendar.getInstance();//当前日期	
		cal.add(Calendar.DATE,-day);
		Date beginDate = cal.getTime();
		String beginDates = sdf.format(beginDate);
		return beginDates;
	}
	
	public static String getDateStart(Integer day){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();//当前日期	
		cal.add(Calendar.DATE,-day);
		Date beginDate = cal.getTime();
		String beginDates = sdf.format(beginDate);
		return beginDates+" 00:00:00";
	}
	
	public static Integer getYear(){
		Calendar cal = Calendar.getInstance();//当前日期	
		return cal.get(Calendar.YEAR);
	}
	
	public static Integer getMonth(){
		Calendar cal = Calendar.getInstance();//当前日期	
		return cal.get(Calendar.MONTH)+1;
	}
	
	 
	 /** 
	  * 得到指定月的天数 
	  * */  
	 public static int getMonthLastDay(int year, int month)  
	 {  
	     Calendar a = Calendar.getInstance();  
	     a.set(Calendar.YEAR, year);  
	     a.set(Calendar.MONTH, month - 1);  
	     a.set(Calendar.DATE, 1);//把日期设置为当月第一天  
	     a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天  
	     int maxDate = a.get(Calendar.DATE);  
	     return maxDate;  
	 }
	 
	 public static String stringToString(String dateStr){
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddhh"); 
		SimpleDateFormat df3 = new SimpleDateFormat("yyyy年MM月dd日 HH时"); 
		Date d = null;
		try {
			d = df2.parse(dateStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return df3.format(d);
	 }
	 
	 /**
		 * 获得一个月的最后一天
		 */
		public static String getEnddate(Integer year,Integer month) {
			Calendar cal = new GregorianCalendar();
			if(year != null && !year.equals("")){
				cal.set(Calendar.YEAR,year);
			}else{
				year = cal.get(Calendar.YEAR);
			}
			if(month != null && !month.equals("")){
				cal.set(Calendar.MONTH, month-1);
			}else{
				month = cal.get(Calendar.MONTH);
			}
			String monthstr = month + "";
			if (monthstr.length() == 1) {
				monthstr = "0" + month;
			}
			// 获得当前月的天数
			int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
			String enddate = year + "-" + monthstr + "-" + days;
			return enddate;
		}

		/**
		 * 获得一个月的最前一天
		 */
		public static String getBegindate(Integer year,Integer month) {
			Calendar cal = new GregorianCalendar();
			if(year != null && !year.equals("")){
				cal.set(Calendar.YEAR,year);
			}else{
				year = cal.get(Calendar.YEAR);
			}
			if(month != null && !month.equals("")){
				cal.set(Calendar.MONTH, month-1);
			}else{
				month = cal.get(Calendar.MONTH);
			}
			String monthstr = month + "";
			if (monthstr.length() == 1) {
				monthstr = "0" + month;
			}
			String begindate = year + "-" + monthstr + "-01";
			return begindate;
		}
		
		/**
		 * 获得一个月的最后一天
		 */
		public static String getEnddate() {
			Calendar cal = new GregorianCalendar();
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH) + 1;
			if (month == 13)
				month = 12;
			// 获得当前月的天数
			int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
			String enddate = year + "-" + month + "-" + days;
			return enddate;
		}

		/**
		 * 获得一个月的最前一天
		 */
		public static String getBegindate() {
			Calendar cal = new GregorianCalendar();
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH) + 1;
			if (month == 13)
				month = 12;
			String monthstr = month + "";
			if (monthstr.length() == 1) {
				monthstr = "0" + month;
			}
			String begindate = year + "-" + monthstr + "-01";
			return begindate;
		}

		
		/**
		 * 判断 beforeDate 是否在 lastDate 之后
		 * @param beforeDate
		 * @param lastDate
		 * @return
		 */
		public static boolean after(String beforeDate,String lastDate,String gs){
			SimpleDateFormat sdf = new SimpleDateFormat(gs);
			try {
				return sdf.parse(beforeDate).after(sdf.parse(lastDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return false;
		}
		
		/**
		 * 判断 beforeDate 是否在 lastDate 之前
		 * @param beforeDate
		 * @param lastDate
		 * @return
		 */
		public static boolean before(String beforeDate,String lastDate,String gs){
			SimpleDateFormat sdf = new SimpleDateFormat(gs);
			try {
				return sdf.parse(beforeDate).before(sdf.parse(lastDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return false; 
		} 
		
		/**
		 * 比较两个日期的大小，0相等，1 大于 -1 小于
		 * @param beforeDate
		 * @param lastDate
		 * @return
		 */
		public static int compareTo(String beforeDate,String lastDate,String gs){
			SimpleDateFormat sdf = new SimpleDateFormat(gs);
			try {
				return sdf.parse(beforeDate).compareTo(sdf.parse(lastDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return 0; 
		} 
		
		/**
		 * 判断 nowDate 是否在 beingDate 和endDate 之间
		 * @param nowDate
		 * @param beginDate
		 * @param endDate
		 * @return
		 */
		public static boolean between(String nowDate ,String beginDate,String endDate,String gs){
			if(after(nowDate, beginDate,gs) && before(nowDate, endDate,gs)){
				return true;
			}else{
				return false;
			}
		}
		
		public static long timePoor(String beforeDate,String afterDate,String gs){
			try{
				SimpleDateFormat time = new SimpleDateFormat(gs);
			    Date d1 = time.parse(afterDate);
			    Date d2 = time.parse(beforeDate);
			    long diff = d1.getTime() - d2.getTime();
			    long days = diff / (1000 * 60 * 60 * 24);
			    return days;
			}catch (Exception e){
				return 0;
			}
		}
		
		public static double timePoorDouble(String beforeDate,String afterDate,String gs){
			try{
				SimpleDateFormat time = new SimpleDateFormat(gs);
			    Date d1 = time.parse(afterDate);
			    Date d2 = time.parse(beforeDate);
			    double diff = d1.getTime() - d2.getTime();
			    double days = Double.parseDouble(""+diff / (1000 * 60 * 60 * 24));
			    BigDecimal   b   =   new   BigDecimal(days);  
			    double   f1   =   b.setScale(1,   BigDecimal.ROUND_HALF_UP).doubleValue();
			    return f1;
			}catch (Exception e){
				return 0;
			}
		}
		
		public static String timeAdd(String beforeDate,Integer days){
			try{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Calendar c = Calendar.getInstance();
				c.setTime(sdf.parse(beforeDate));
				c.add(Calendar.DATE,days);
			    return sdf.format(c.getTime());
			}catch (Exception e){
				return null;
			}
		}
		
		 /**  
	     * @param args  
	     */  
	    public static void main(String[] args) {   
	    	System.out.println(getCurrentDateNoLine());
	    }   
//	    /**  
//	     * 获取两个时间之内的工作日时间（只去掉两个日期之间的周末时间，法定节假日未去掉）  
//	     * @param start -起始时间，共有3个重载方法，可以传入long型，Long型，与Date型  
//	     * @param end -结束时间，共有3个重载方法，可以传入long型，Long型，与Date型  
//	     * @return Long型时间差对象  
//	     */  
//	    public static Long getWorkdayTimeInMillis(long start, long end){   
//	        //如果起始时间大于结束时间，将二者交换   
//	        if(start>end){   
//	            long temp = start;   
//	            start = end;   
//	            end = temp;   
//	        }   
//	        //根据参数获取起始时间与结束时间的日历类型对象   
//	        Calendar sdate = Calendar.getInstance();   
//	        Calendar edate = Calendar.getInstance();   
//	        sdate.setTimeInMillis(start);   
//	        edate.setTimeInMillis(end);   
//	        //如果两个时间在同一周并且都不是周末日期，则直接返回时间差，增加执行效率   
//	        if(sdate.get(Calendar.YEAR)==edate.get(Calendar.YEAR)   
//	                && sdate.get(Calendar.WEEK_OF_YEAR)==edate.get(Calendar.WEEK_OF_YEAR)   
//	                && sdate.get(Calendar.DAY_OF_WEEK)!=1 && sdate.get(Calendar.DAY_OF_WEEK)!=7  
//	                && edate.get(Calendar.DAY_OF_WEEK)!=1 && edate.get(Calendar.DAY_OF_WEEK)!=7){   
//	            return new Long(end-start);   
//	        }   
//	        //首先取得起始日期与结束日期的下个周一的日期   
//	        Calendar snextM = getNextMonday(sdate);   
//	        Calendar enextM = getNextMonday(edate);   
//	        //获取这两个周一之间的实际天数   
//	        int days = getDaysBetween(snextM, enextM);   
//	        //获取这两个周一之间的工作日数(两个周一之间的天数肯定能被7整除，并且工作日数量占其中的5/7)   
//	        int workdays = days/7*5;   
//	        //获取开始时间的偏移量   
//	        long scharge = 0;   
//	        if(sdate.get(Calendar.DAY_OF_WEEK)!=1 && sdate.get(Calendar.DAY_OF_WEEK)!=7){   
//	            //只有在开始时间为非周末的时候才计算偏移量   
//	            scharge += (7-sdate.get(Calendar.DAY_OF_WEEK))*24*3600000;   
//	            scharge -= sdate.get(Calendar.HOUR_OF_DAY)*3600000;   
//	            scharge -= sdate.get(Calendar.MINUTE)*60000;   
//	            scharge -= sdate.get(Calendar.SECOND)*1000;   
//	            scharge -= sdate.get(Calendar.MILLISECOND);   
//	        }   
//	        //获取结束时间的偏移量   
//	        long echarge = 0;   
//	        if(edate.get(Calendar.DAY_OF_WEEK)!=1 && edate.get(Calendar.DAY_OF_WEEK)!=7){   
//	            //只有在结束时间为非周末的时候才计算偏移量   
//	            echarge += (7-edate.get(Calendar.DAY_OF_WEEK))*24*3600000;   
//	            echarge -= edate.get(Calendar.HOUR_OF_DAY)*3600000;   
//	            echarge -= edate.get(Calendar.MINUTE)*60000;   
//	            echarge -= edate.get(Calendar.SECOND)*1000;   
//	            echarge -= edate.get(Calendar.MILLISECOND);   
//	        }   
//	        //计算最终结果，具体为：workdays加上开始时间的时间偏移量，减去结束时间的时间偏移量   
//	        return workdays*24*3600000+scharge-echarge;   
//	    }   
//	    public static Long getWorkdayTimeInMillis(Long start, Long end){   
//	        return getWorkdayTimeInMillis(start.longValue(), end.longValue());   
//	    }   
//	    public static Long getWorkdayTimeInMillis(Date start, Date end){   
//	        return getWorkdayTimeInMillis(start.getTime(), end.getTime());   
//	    }   
//	    public static Long getWorkdayTimeInMillis(String start, String end, String format){   
//	        SimpleDateFormat sdf = new SimpleDateFormat(format);   
//	        Date sdate;   
//	        Date edate;   
//	        try {   
//	            sdate = sdf.parse(start);   
//	            edate = sdf.parse(end);   
//	            return getWorkdayTimeInMillis(sdate, edate);   
//	        } catch (ParseException e) {   
//	            e.printStackTrace();   
//	            return new Long(0);   
//	        }   
//	    }   
//	    private static Calendar getNextMonday(Calendar cal){   
//	        int addnum=9-cal.get(Calendar.DAY_OF_WEEK);   
//	        if(addnum==8)addnum=1;//周日的情况   
//	        cal.add(Calendar.DATE, addnum);   
//	        return cal;   
//	    }   
//	    /**  
//	     * 获取两个日期之间的实际天数，支持跨年  
//	     */  
//	    public static int getDaysBetween(Calendar start, Calendar end){   
//	        if(start.after(end)){   
//	            Calendar swap = start;   
//	            start = end;   
//	            end = swap;   
//	        }   
//	        int days = end.get(Calendar.DAY_OF_YEAR)- start.get(Calendar.DAY_OF_YEAR);   
//	        int y2 = end.get(Calendar.YEAR);   
//	        if (start.get(Calendar.YEAR) != y2) {   
//	            start = (Calendar) start.clone();   
//	            do {   
//	                days += start.getActualMaximum(Calendar.DAY_OF_YEAR);   
//	                start.add(Calendar.YEAR, 1);   
//	            }while(start.get(Calendar.YEAR) != y2);   
//	        }   
//	        return days;   
//	    }   
		
}
